package com.zhang.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AbsoluteLayout;
import android.widget.Button;

public class FloatButtonActivity extends Activity {
	AbsoluteLayout mLayoutGroup = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.main);

		mLayoutGroup = new AbsoluteLayout(this);
		AbsoluteLayout.LayoutParams layoutParams = new AbsoluteLayout.LayoutParams(320, 480, 0, 0);

		setContentView(mLayoutGroup, layoutParams);

		Button button = new Button(this);
		button.setText("testButton");
		layoutParams = new AbsoluteLayout.LayoutParams(120, 60, 20, 20);
		mLayoutGroup.addView(button, layoutParams);
		button.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				// alert();
			}
		});
		button.setOnTouchListener(touchListener);

		final Button btButton = new Button(this);
		btButton.setText("测试按钮移动");
		layoutParams = new AbsoluteLayout.LayoutParams(120, 60, 20, 160);
		mLayoutGroup.addView(btButton, layoutParams);
		btButton.setOnTouchListener(touchListener);
	}

	OnTouchListener touchListener = new OnTouchListener() {
		int temp[] = new int[] { 0, 0 };

		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			int eventAction = event.getAction();
			Log.e("testButtonMove", "OnTouchAction:" + eventAction);

			int x = (int) event.getRawX();
			int y = (int) event.getRawY();

			switch (eventAction) {
			case MotionEvent.ACTION_DOWN:

				temp[0] = (int) event.getX();
				temp[1] = (int) (y - v.getTop());

				mLayoutGroup.bringChildToFront(v);
				v.postInvalidate();

				break;
			case MotionEvent.ACTION_MOVE:

				int left = x - temp[0];
				int top = y - temp[1];
				int right = left + v.getWidth();
				int bottom = top + v.getHeight();

				v.layout(left, top, right, bottom);
				v.postInvalidate();

				break;

			default:
				break;
			}

			return false;
		}
	};

	void alert() {
		new AlertDialog.Builder(this)
				.setNeutralButton("OK", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub

					}
				}).setTitle("test button").setMessage("test test test!!!")
				.show();
	}

}
